package lueder.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lueder.classes.ShoppingCart;

/**
 * Servlet implementation class ShoppingCartServlet
 */
public class ShoppingCartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ShoppingCartServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		ShoppingCart cart = null;
		int totalAmount = 0;
		String totalAmountString = "item";
		DecimalFormat f = new DecimalFormat("#0.00"); 
		double totalPrice = 0.0;
		if(request.getSession(false)!=null)
		{
			cart = (ShoppingCart)request.getSession(false).getAttribute("cart");
			totalAmount = cart.getTotalAmount();
			totalAmountString = (totalAmount > 1)?"items": "item";
			totalPrice = cart.computePrice();
		}
		
		String path = request.getContextPath()+"/";
		
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<div class='cart'>");
		out.println("<div class='title'><span class='title_icon'><img src='"+path+"images/cart.gif' alt='' title='' /></span>My cart</div>");
		out.println("<div class='home_cart_content'>");
		out.println(totalAmount+" x "+totalAmountString+" | <span class='red'>TOTAL: "+f.format(totalPrice)+"EUR</span>");
		out.println("</div>");
		out.println("<a href='"+path+"ShoppingCart' class='view_cart'>view cart</a>");
		out.println("");
		out.println("</div>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
